"""
Gua框架日志系统 - 生产环境配置示例
基于Linus设计哲学：简单、可靠、实用
"""

import asyncio
import time
import random
import traceback
from gua import GuaApp, GuaLogger, LoggingMiddleware, SimpleMonitor, json

# 创建应用
app = GuaApp()

# 生产环境日志配置
logger = GuaLogger(
    name="production_app",
    output="file",  # 文件输出，适合生产环境
    file_path="app.log",  # 日志文件路径
)

# 创建性能监控
monitor = SimpleMonitor(logger, max_samples=5000)  # 增加样本数量

# 添加日志中间件，设置更严格的慢请求阈值
app.use(LoggingMiddleware(logger, slow_threshold=0.8))

# 设置全局默认日志记录器
from gua import set_default_logger

set_default_logger(logger)


@app.route("/")
async def home():
    """首页 - 生产环境日志"""
    logger.info("page_view", page="home", referrer="direct")
    return {"message": "Welcome to Production App"}


@app.route("/api/users")
async def get_users():
    """用户API - 记录业务指标"""
    start_time = time.time()

    # 模拟数据库查询
    await asyncio.sleep(0.1)
    users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]

    # 记录业务指标
    logger.info(
        "api_success",
        endpoint="/api/users",
        method="GET",
        user_count=len(users),
        db_query_time=0.1,
        total_time=time.time() - start_time,
    )

    return json(users)


@app.route("/api/orders")
async def get_orders():
    """订单API - 错误处理示例"""
    logger.info("orders_request_started", user_id="user123")

    try:
        # 模拟可能的错误
        if random.random() < 0.3:  # 30%概率出错
            raise ConnectionError("Database connection failed")

        # 正常情况
        await asyncio.sleep(0.2)
        orders = [{"id": 1, "total": 99.99}, {"id": 2, "total": 149.99}]

        logger.info(
            "orders_retrieved",
            user_id="user123",
            order_count=len(orders),
            total_value=sum(o["total"] for o in orders),
        )

        return json(orders)

    except Exception as e:
        logger.error(
            "orders_error",
            user_id="user123",
            error_type=type(e).__name__,
            error_message=str(e),
        )
        return json({"error": "Unable to fetch orders"}, status=500)


@app.route("/health")
async def health_check():
    """健康检查 - 不记录详细日志"""
    # 健康检查使用DEBUG级别，避免在生产环境产生噪音
    logger.debug("health_check")
    return {"status": "healthy", "timestamp": time.time()}


@app.route("/metrics")
async def metrics():
    """性能指标API"""
    stats = monitor.get_stats()

    # 记录指标查询
    logger.info("metrics_accessed", stats=stats)

    return {
        "performance": stats,
        "system": {
            "uptime": time.time() - start_time,
            "memory_usage": "N/A",  # 可以添加实际内存监控
        },
    }


# 错误处理中间件示例
@app.middleware
async def error_handler_middleware(app):
    async def wrapper(scope, receive, send):
        try:
            await app(scope, receive, send)
        except Exception as e:
            # 记录未处理的异常
            logger.error(
                "unhandled_exception",
                path=scope.get("path", "unknown"),
                method=scope.get("method", "unknown"),
                error_type=type(e).__name__,
                error_message=str(e),
                traceback=traceback.format_exc(),
            )

            # 发送错误响应
            from gua import send_error

            await send_error(send, "Internal Server Error", 500)

    return wrapper


# 添加错误处理中间件
app.use(error_handler_middleware)

# 全局变量
start_time = time.time()

if __name__ == "__main__":
    import subprocess
    import sys
    
    # 使用gua命令显示示例启动信息
    result = subprocess.run([sys.executable, "-m", "gua.cli", "examples.production_logging:app", "--example-info"],
                          capture_output=True, text=True)
    if result.returncode == 0:
        print(result.stdout)
    else:
        print("错误: 无法显示启动信息")
        print("请手动运行: gua examples.production_logging:app --example-info")
